<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import * as echarts from 'echarts/core'
import { BarChart, LineChart, PieChart, RadarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent,
  ToolboxComponent,
  GraphicComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { ElMessage } from 'element-plus'
import {
  HomeFilled,
  Clock,
  Refresh,
  Search,
  Download,
  Filter,
  DataAnalysis,
  Histogram,
  PieChart as PieChartIcon,
  Platform
} from '@element-plus/icons-vue'

// 导入ECharts类型
import type { EChartsType } from 'echarts/core'

// 注册必要的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent,
  ToolboxComponent,
  GraphicComponent,
  BarChart,
  LineChart,
  PieChart,
  RadarChart,
  CanvasRenderer
])

// 数据加载状态
const loading = ref(false)

// 平台列表
const platforms = ref([
  { id: 1, name: '微博', color: '#E6162D' },
  { id: 2, name: '微信', color: '#07C160' },
  { id: 3, name: '抖音', color: '#000000' },
  { id: 4, name: '知乎', color: '#0066FF' },
  { id: 5, name: '小红书', color: '#FE2C55' }
])

// 选中的平台
const selectedPlatforms = ref([1, 2, 3])

// 时间范围
const dateRange = ref([
  new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
  new Date().toISOString().split('T')[0]
])

// 图表引用
const userChartRef = ref<HTMLElement | null>(null)
const contentChartRef = ref<HTMLElement | null>(null)
const sentimentChartRef = ref<HTMLElement | null>(null)
const engagementChartRef = ref<HTMLElement | null>(null)

// 图表实例
const userChart = ref<EChartsType | null>(null)
const contentChart = ref<EChartsType | null>(null)
const sentimentChart = ref<EChartsType | null>(null)
const engagementChart = ref<EChartsType | null>(null)

// 当前时间
const currentTime = ref(new Date())
const formattedTime = computed(() => {
  const options: Intl.DateTimeFormatOptions = { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit', 
    minute: '2-digit', 
    second: '2-digit',
    hour12: false
  }
  return new Intl.DateTimeFormat('zh-CN', options).format(currentTime.value)
})

// 更新当前时间
const updateTime = () => {
  currentTime.value = new Date()
}

// 刷新数据
const refreshData = async () => {
  if (selectedPlatforms.value.length === 0) {
    ElMessage.warning('请至少选择一个平台进行对比')
    return
  }

  loading.value = true
  try {
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 初始化图表
    initUserChart()
    initContentChart()
    initSentimentChart()
    initEngagementChart()
    
    ElMessage.success('数据刷新成功')
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('数据刷新失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 导出数据
const exportData = () => {
  ElMessage.success('数据导出成功')
}

// 初始化用户数量图表
const initUserChart = () => {
  if (!userChartRef.value) return
  
  if (userChart.value) {
    userChart.value.dispose()
  }
  
  userChart.value = echarts.init(userChartRef.value)
  
  // 生成日期数据
  const days = 30
  const dates: string[] = []
  for (let i = days; i >= 0; i--) {
    const date = new Date()
    date.setDate(date.getDate() - i)
    dates.push(date.toISOString().split('T')[0].substring(5)) // 只显示月-日
  }
  
  // 生成模拟数据
  const series = selectedPlatforms.value.map(platformId => {
    const platform = platforms.value.find(p => p.id === platformId)
    if (!platform) return {} // 添加空对象防止平台未找到
    
    const baseValue = Math.floor(Math.random() * 5000) + 1000
    const data = dates.map(() => Math.floor(baseValue + Math.random() * baseValue * 0.5))
    
    return {
      name: platform.name,
      type: 'line',
      data: data,
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      itemStyle: {
        color: platform.color
      }
    }
  })
  
  const option = {
    title: {
      text: '活跃用户数量趋势对比',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: selectedPlatforms.value.map(id => {
        const platform = platforms.value.find(p => p.id === id)
        return platform ? platform.name : ''
      }),
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates,
      axisLabel: {
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '用户数量',
      axisLabel: {
        formatter: (value: number) => {
          if (value >= 10000) {
            return (value / 10000).toFixed(1) + '万'
          }
          return value
        }
      }
    },
    series: series
  }
  
  userChart.value.setOption(option)
  
  window.addEventListener('resize', () => {
    userChart.value && userChart.value.resize()
  })
}

// 初始化内容数量图表
const initContentChart = () => {
  if (!contentChartRef.value) return
  
  if (contentChart.value) {
    contentChart.value.dispose()
  }
  
  contentChart.value = echarts.init(contentChartRef.value)
  
  // 生成模拟数据
  const series = selectedPlatforms.value.map(platformId => {
    const platform = platforms.value.find(p => p.id === platformId)
    if (!platform) return { name: '', value: 0 } // 添加默认值防止平台未找到
    
    const baseValue = Math.floor(Math.random() * 10000) + 5000
    
    return {
      name: platform.name,
      value: baseValue,
      itemStyle: {
        color: platform.color
      }
    }
  })
  
  const option = {
    title: {
      text: '平台内容数量对比',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: selectedPlatforms.value.map(id => {
        const platform = platforms.value.find(p => p.id === id)
        return platform ? platform.name : ''
      })
    },
    series: [
      {
        name: '内容数量',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {c} ({d}%)'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold'
          }
        },
        data: series
      }
    ]
  }
  
  contentChart.value.setOption(option)
  
  window.addEventListener('resize', () => {
    contentChart.value && contentChart.value.resize()
  })
}

// 初始化情感分布图表
const initSentimentChart = () => {
  if (!sentimentChartRef.value) return
  
  if (sentimentChart.value) {
    sentimentChart.value.dispose()
  }
  
  sentimentChart.value = echarts.init(sentimentChartRef.value)
  
  // 生成模拟数据
  const platformNames = selectedPlatforms.value.map(id => {
    const platform = platforms.value.find(p => p.id === id)
    return platform ? platform.name : ''
  })
  const positiveData = selectedPlatforms.value.map(() => Math.floor(Math.random() * 40) + 30)
  const neutralData = selectedPlatforms.value.map(() => Math.floor(Math.random() * 30) + 20)
  const negativeData = selectedPlatforms.value.map((_id, index) => 100 - positiveData[index] - neutralData[index])
  
  const option = {
    title: {
      text: '平台情感分布对比',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['正面', '中性', '负面'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      }
    },
    yAxis: {
      type: 'category',
      data: platformNames
    },
    series: [
      {
        name: '正面',
        type: 'bar',
        stack: 'total',
        label: {
          show: true,
          formatter: '{c}%'
        },
        emphasis: {
          focus: 'series'
        },
        data: positiveData,
        itemStyle: {
          color: '#67C23A'
        }
      },
      {
        name: '中性',
        type: 'bar',
        stack: 'total',
        label: {
          show: true,
          formatter: '{c}%'
        },
        emphasis: {
          focus: 'series'
        },
        data: neutralData,
        itemStyle: {
          color: '#909399'
        }
      },
      {
        name: '负面',
        type: 'bar',
        stack: 'total',
        label: {
          show: true,
          formatter: '{c}%'
        },
        emphasis: {
          focus: 'series'
        },
        data: negativeData,
        itemStyle: {
          color: '#F56C6C'
        }
      }
    ]
  }
  
  sentimentChart.value.setOption(option)
  
  window.addEventListener('resize', () => {
    sentimentChart.value && sentimentChart.value.resize()
  })
}

// 初始化互动指标图表
const initEngagementChart = () => {
  if (!engagementChartRef.value) return
  
  if (engagementChart.value) {
    engagementChart.value.dispose()
  }
  
  engagementChart.value = echarts.init(engagementChartRef.value)
  
  // 生成模拟数据
  const indicators = [
    { name: '点赞率', max: 100 },
    { name: '评论率', max: 100 },
    { name: '转发率', max: 100 },
    { name: '互动率', max: 100 },
    { name: '曝光率', max: 100 },
    { name: '留存率', max: 100 }
  ]
  
  const series = selectedPlatforms.value.map(platformId => {
    const platform = platforms.value.find(p => p.id === platformId)
    if (!platform) return { name: '', value: [] } // 添加默认值防止平台未找到
    
    return {
      name: platform.name,
      value: indicators.map(() => Math.floor(Math.random() * 80) + 20),
      lineStyle: {
        color: platform.color
      },
      areaStyle: {
        color: {
          type: 'radial',
          x: 0.5,
          y: 0.5,
          r: 0.5,
          colorStops: [
            {
              offset: 0,
              color: platform.color + '80' // 添加透明度
            },
            {
              offset: 1,
              color: platform.color + '10'
            }
          ]
        }
      }
    }
  })
  
  const option = {
    title: {
      text: '平台互动指标对比',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      data: selectedPlatforms.value.map(id => {
        const platform = platforms.value.find(p => p.id === id)
        return platform ? platform.name : ''
      }),
      bottom: 0
    },
    radar: {
      indicator: indicators,
      splitNumber: 4,
      axisName: {
        color: '#333',
        fontSize: 12
      },
      splitArea: {
        areaStyle: {
          color: ['#F6F8FC', '#E9EDF4', '#DCE2ED', '#D0D7E6']
        }
      }
    },
    series: [
      {
        type: 'radar',
        data: series
      }
    ]
  }
  
  if (engagementChart.value) {
    engagementChart.value.setOption(option)
  
    window.addEventListener('resize', () => {
      if (engagementChart.value) {
        engagementChart.value.resize()
      }
    })
  }
}

// 生成详细指标数据
const platformMetrics = computed(() => {
  return selectedPlatforms.value.map(platformId => {
    const platform = platforms.value.find(p => p.id === platformId)
    if (!platform) return { 
      id: 0, 
      name: '', 
      userCount: 0, 
      contentCount: 0, 
      avgEngagement: '0', 
      positiveRate: '0%', 
      neutralRate: '0%', 
      negativeRate: '0%', 
      responseTime: '0小时', 
      growthRate: '0%' 
    }
    
    return {
      id: platform.id,
      name: platform.name,
      userCount: Math.floor(Math.random() * 100000) + 50000,
      contentCount: Math.floor(Math.random() * 50000) + 10000,
      avgEngagement: (Math.random() * 10 + 5).toFixed(2),
      positiveRate: (Math.random() * 40 + 30).toFixed(1) + '%',
      neutralRate: (Math.random() * 30 + 20).toFixed(1) + '%',
      negativeRate: (Math.random() * 20 + 10).toFixed(1) + '%',
      responseTime: (Math.random() * 10 + 1).toFixed(1) + '小时',
      growthRate: (Math.random() * 10 - 2).toFixed(1) + '%'
    }
  })
})

// 获取平台颜色
const getPlatformColor = (id: number): string => {
  const platform = platforms.value.find(p => p.id === id)
  return platform ? platform.color : '#909399'
}

// 监听平台选择变化
watch(selectedPlatforms, () => {
  if (selectedPlatforms.value.length > 0) {
    refreshData()
  }
}, { deep: true })

// 监听日期范围变化
watch(dateRange, () => {
  refreshData()
}, { deep: true })

// 组件挂载时
onMounted(() => {
  // 每秒更新时间
  setInterval(updateTime, 1000)
  
  // 初始化数据
  refreshData()
})
</script>

<template>
  <div class="platform-comparison-view">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-container">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">
          <el-icon><HomeFilled /></el-icon> 首页
        </el-breadcrumb-item>
        <el-breadcrumb-item>平台数据对比</el-breadcrumb-item>
      </el-breadcrumb>
      
      <div class="current-time">
        <el-icon><Clock /></el-icon>
        <span>{{ formattedTime }}</span>
      </div>
    </div>
    
    <!-- 页面标题和控制区 -->
    <div class="page-header">
      <div class="title-section">
        <h1 class="page-title">平台数据对比</h1>
        <div class="page-description">
          对比分析不同平台的用户、内容、情感和互动数据
        </div>
      </div>
      
      <div class="header-actions">
        <el-button type="info" plain :icon="Download" @click="exportData">导出数据</el-button>
        <el-button type="primary" :icon="Refresh" :loading="loading" @click="refreshData">
          刷新数据
        </el-button>
      </div>
    </div>
    
    <!-- 全局加载状态 -->
    <div class="loading-overlay" v-if="loading">
      <el-icon class="loading-icon"><Refresh class="is-loading" /></el-icon>
      <div class="loading-text">数据加载中...</div>
    </div>
    
    <!-- 过滤器区域 -->
    <div class="filter-container">
      <div class="filter-section">
        <div class="filter-label">选择平台：</div>
        <div class="filter-content">
          <el-checkbox-group v-model="selectedPlatforms">
            <el-checkbox 
              v-for="platform in platforms" 
              :key="platform.id" 
              :label="platform.id"
              :style="{ color: platform.color }"
            >
              {{ platform.name }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      
      <div class="filter-section">
        <div class="filter-label">时间范围：</div>
        <div class="filter-content">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 350px;"
          />
        </div>
      </div>
    </div>
    
    <!-- 图表区域 -->
    <div class="charts-container">
      <el-row :gutter="20">
        <el-col :xs="24" :lg="12">
          <el-card shadow="hover" class="chart-card">
            <div ref="userChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
        
        <el-col :xs="24" :lg="12">
          <el-card shadow="hover" class="chart-card">
            <div ref="contentChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
        
        <el-col :xs="24" :lg="12">
          <el-card shadow="hover" class="chart-card">
            <div ref="sentimentChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
        
        <el-col :xs="24" :lg="12">
          <el-card shadow="hover" class="chart-card">
            <div ref="engagementChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 详细指标表格 -->
    <el-card shadow="hover" class="metrics-table-card">
      <template #header>
        <div class="card-header">
          <span>平台指标详细对比</span>
        </div>
      </template>
      
      <el-table :data="platformMetrics" border style="width: 100%" stripe>
        <el-table-column prop="name" label="平台名称" width="120">
          <template #default="scope">
            <div class="platform-name" :style="{ color: getPlatformColor(scope.row.id) }">
              {{ scope.row.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="userCount" label="活跃用户数" sortable>
          <template #default="scope">
            {{ scope.row.userCount.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="contentCount" label="内容数量" sortable>
          <template #default="scope">
            {{ scope.row.contentCount.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="avgEngagement" label="平均互动量" sortable />
        <el-table-column prop="positiveRate" label="正面情感占比" sortable />
        <el-table-column prop="neutralRate" label="中性情感占比" sortable />
        <el-table-column prop="negativeRate" label="负面情感占比" sortable />
        <el-table-column prop="responseTime" label="平均响应时间" sortable />
        <el-table-column prop="growthRate" label="用户增长率" sortable>
          <template #default="scope">
            <span :class="parseFloat(scope.row.growthRate) >= 0 ? 'positive-growth' : 'negative-growth'">
              {{ scope.row.growthRate }}
            </span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<style scoped>
.platform-comparison-view {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.breadcrumb-container {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.current-time {
  font-size: 13px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 5px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.title-section {
  display: flex;
  flex-direction: column;
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0;
  margin-bottom: 8px;
}

.page-description {
  font-size: 14px;
  color: #909399;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-icon {
  font-size: 48px;
  color: var(--el-color-primary);
  animation: rotating 2s linear infinite;
}

.is-loading {
  animation: rotating 2s linear infinite;
}

.loading-text {
  margin-top: 15px;
  font-size: 16px;
  color: var(--el-text-color-primary);
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.filter-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.filter-section {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.filter-section:last-child {
  margin-bottom: 0;
}

.filter-label {
  width: 100px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.filter-content {
  flex: 1;
}

.charts-container {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.chart-container {
  height: 350px;
  width: 100%;
}

.metrics-table-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.platform-name {
  font-weight: 500;
}

.positive-growth {
  color: #67C23A;
}

.negative-growth {
  color: #F56C6C;
}
</style> 